package com.leesche.zcsp.node.web.service.impl.data.aop.redis;

import com.leesche.zcsp.node.cache.JedisUtil;
import com.leesche.zcsp.node.net.service.data.NetDevice;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDeviceDto;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 设备表切面拦截器
 * @author reid
 * @Created 16/12/13
 */
@Aspect
@Component
public class DeviceServiceAspect {
    public static final Logger LOGGER = Logger.getLogger(DeviceServiceAspect.class);
//    @Autowired
//    private PubDeviceService pubDeviceService;

    @Pointcut("target(com.leesche.zcsp.node.web.service.PubDeviceService) && (execution(* insert*(..)) || execution(* edit*(..)) || execution(* add*(..)) || execution(* update*(..)) || execution(* delete*(..)))")
    public void deviceAspect() {
        LOGGER.info("设备表数据库操作切入点......");
    }


    @AfterReturning(pointcut = "deviceAspect()", returning = "retValue")
    public void doAfter(JoinPoint joinPoint, Object retValue) {
        String method = joinPoint.getSignature().getName();
        int ret = Integer.parseInt(retValue.toString());

        try {
            if (ret > 0) {
                if (method.startsWith("delete")) {
                    LOGGER.info("拦截到设备表删除操作,开始更新redis 缓存......");
                    String param = joinPoint.getArgs()[0].toString();//deviceId
                    PubDeviceDto deviceDto = JedisUtil.hget("deviceMap", param, new PubDeviceDto());
                    JedisUtil.hdel("deviceMap", param);
                    JedisUtil.hdel("netDeviceMap", deviceDto.getImme());
                } else {
                    if (joinPoint.getArgs()[0] instanceof PubDevice) {
                        LOGGER.info("拦截到设备表增加/更新操作,开始更新redis 缓存......");
                        PubDevice device = (PubDevice) joinPoint.getArgs()[0];
                        if (device != null && device.getDeviceid() != null) {
                            JedisUtil.hset("deviceMap", String.valueOf(device.getDeviceid()), device);
                            JedisUtil.hset("netDeviceMap", device.getImme(), new NetDevice(
                                    device.getDeviceid(), device.getAdminid(), device.getPlaceid(), device.getIsonline()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("更新redis 缓存失败...");
        }

    }

}
